<template>
  <view class="container">
    <!-- 主内容 -->
    <view class="content">
      <!-- 积分信息卡片 -->
      <view class="info-cards">
        <view class="info-card yellow">
          <text class="card-title">自己分配积分</text>
          <text class="card-value">您已收到自己分配的积分: {{ leaderPoints || 0 }}</text>
        </view>
        
        <view class="info-card blue">
          <text class="card-title">待分配积分</text>
          <text class="card-value">您还有 {{ remainingPoints || 0 }} 积分可分配给组员</text>
        </view>
      </view>
      
      <!-- 添加组员 -->
      <view class="add-member-section">
        <text class="section-title">添加组员</text>
        <button class="add-btn" @click="openAddMemberDialog">添加组员</button>
		<view>分配给自己 </view>
		
		<view class="member-operation" style="margin-top: 20rpx;">
		  <input 
		    type="number" 
		    placeholder="分配积分" 
		    class="points-input"
		    v-model="assignPoints"
		  />
		  <input
		    type="text" 
		    placeholder="积分描述" 
		    class="remark-input"
		    v-model="remark"
		  />
		  <button class="distribute-btn" @click="handleAssignBySelf()">分配</button>
		</view>
      </view>
      
      <!-- 组员列表 -->
      <view class="members-section">
        <text class="section-title">组员列表与积分分配</text>
        
        <!-- 组员列表 -->
        <view class="members-list">
          <view class="member-item" v-for="member in memberList" :key="member.userId">
            <view class="member-info">
              <image src="/static/images/member-avatar.png" mode="widthFix" class="member-avatar"></image>
              <text class="member-name">{{ member.nickName || member.userName }}</text>
              <text class="member-points">分配所得: {{ member.allocatedIntegral || 0 }}</text>
            </view>
            
            <view class="member-operation">
              <input 
                type="number" 
                placeholder="分配积分" 
                class="points-input"
                v-model="member.assignPoints"
              />
			   <!-- 新增：备注输入框 -->
			    <input 
			      type="text" 
			      placeholder="积分描述" 
			      class="remark-input"
			      v-model="member.remark"
			    />
              <button class="distribute-btn" @click="handleAssign(member)">分配</button>
              <button class="delete-btn" @click="handleDelete(member.orgId)">移除</button>
            </view>
          </view>
          
          <!-- 无组员提示 -->
          <view class="empty-tip" v-if="memberList.length === 0">
            暂无组员数据，点击"添加组员"按钮添加
          </view>
        </view>
      </view>
    </view>

    <!-- 组员选择弹框（带搜索功能） -->
    <view class="dialog-mask" v-if="showUserDialog">
      <view class="dialog-container">
        <view class="dialog-header">
          <text class="dialog-title">选择组员（可多选）</text>
          <text class="dialog-close" @click="showUserDialog = false">×</text>
        </view>
        
        <!-- 搜索框 -->
        <view class="dialog-search">
          <input 
            type="text" 
            placeholder="搜索昵称..." 
            class="search-input"
            v-model="searchKey"
            @input="handleSearch"
          />
        </view>
        
        <!-- 用户列表（可滚动） -->
        <view class="dialog-body">
          <view 
            class="user-item" 
            v-for="user in filteredUsers" 
            :key="user.userId"
            :class="{ 'selected': selectedUserIds.includes(user.userId) }"
            @click="toggleUserSelection(user.userId)"
          >
            <view class="user-info">
              <text class="user-name">{{ user.nickName || user.userName }}</text>
              <text class="user-id">ID: {{ user.userId }}</text>
            </view>
            <view class="user-check" v-if="selectedUserIds.includes(user.userId)">✓</view>
          </view>
          
          <!-- 无数据提示 -->
          <view class="empty-tip" v-if="filteredUsers.length === 0">
            暂无匹配的用户
          </view>
        </view>
        
        <!-- 弹框底部按钮 -->
        <view class="dialog-footer">
          <view class="selected-count" v-if="selectedUserIds.length > 0">
            已选择: {{ selectedUserIds.length }}人
          </view>
          <button class="cancel-btn" @click="showUserDialog = false">取消</button>
          <button class="confirm-btn" @click="confirmAddMembers" :disabled="selectedUserIds.length === 0">
            确认添加
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import { http } from '../../../../utils/requestUtil';
//给自动
const assignPoints = ref(0)
const remark =ref('')
// 响应式变量
const orgId = ref()
const memberList = ref([]) // 组员列表
const leaderPoints = ref(0) // 团长分配给当前组长的积分
const remainingPoints = ref(0) // 剩余可分配积分

// 弹框相关
const showUserDialog = ref(false)
const allAvailableUsers = ref([]) // 所有可添加的用户（用于搜索过滤）
const selectedUserIds = ref([]) // 选中的用户ID
const searchKey = ref('') // 搜索关键词

// 计算属性：根据搜索关键词过滤用户
const filteredUsers = computed(() => {
  if (!searchKey.value) {
    return allAvailableUsers.value // 无搜索词时返回全部
  }
  const key = searchKey.value.toLowerCase()
  return allAvailableUsers.value.filter(user => {
    const userName = (user.userName || '').toLowerCase()
    const nickName = (user.nickName || '').toLowerCase()
    return userName.includes(key) || nickName.includes(key)
  })
})

// 页面加载时获取数据
onLoad((options) => {
  console.log('接收的参数:', options)
  if (options.orgId) {
    orgId.value = options.orgId
    loadData(options.orgId) // 加载当前组数据
  } else {
    uni.showToast({ title: '缺少参数orgId', icon: 'none' })
  }
})

// 加载组数据（组长信息、组员列表、积分情况）
const loadData = async (groupId) => {
  try {
    // 1. 获取组长自身的积分信息（从团长处获得的积分）
    const leaderRes = await http.get(`/integral/organization/user?userId=${uni.getStorageSync("userId")}`)
    if (leaderRes.code === 200) {
      leaderPoints.value = leaderRes.data.allocatedIntegral || 0
      remainingPoints.value = leaderRes.data.points || 0
    }

    // 2. 获取当前组的组员列表
    const membersRes = await http.get(`/integral/organization/getByParentId?parentId=${groupId}`)
    if (membersRes.code === 200 && membersRes.data) {
      // 给每个组员添加临时的积分输入字段
      memberList.value = membersRes.data.map(member => ({
        ...member,
        assignPoints: '',
		  remark: ''  // 新增：备注属性
      }))
    }
  } catch (error) {
    console.error('数据加载失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}

// 打开添加组员弹框（加载可添加的用户）
const openAddMemberDialog = async () => {
  try {
    // 获取已有的组员ID（用于过滤）
    const existingUserIds = memberList.value.map(m => m.userId)
    // 添加上当前登录用户ID（避免自己被添加）
    existingUserIds.push(uni.getStorageSync("userId"))

    // 调用接口获取可添加的用户
    const res = await http.get(`/system/role/authUser/memberList?pageNum=1&pageSize=1000&userName=test`)
    if (res.code === 200 && res.rows) {
      // 过滤掉已在组内的用户和自己
      allAvailableUsers.value = res.rows.filter(user => 
        !existingUserIds.includes(user.userId)
      )
      showUserDialog.value = true
      selectedUserIds.value = []
      searchKey.value = '' // 重置搜索词
    } else {
      uni.showToast({ title: '用户数据加载失败', icon: 'none' })
    }
  } catch (error) {
    console.error('加载可用用户失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}

// 搜索输入处理（借助计算属性自动过滤，无需额外逻辑）
const handleSearch = async(value) =>{
  try {
    // 获取已有的组员ID（用于过滤）
    const existingUserIds = memberList.value.map(m => m.userId)
    // 添加上当前登录用户ID（避免自己被添加）
    existingUserIds.push(uni.getStorageSync("userId"))

    // 调用接口获取可添加的用户
    const res = await http.get(`/system/role/authUser/memberList?pageNum=1&pageSize=1000&userName=${value.detail.value}`)
    if (res.code === 200 && res.rows) {
      // 过滤掉已在组内的用户和自己
      allAvailableUsers.value = res.rows.filter(user => 
        !existingUserIds.includes(user.userId)
      )
      showUserDialog.value = true
      selectedUserIds.value = []
      // searchKey.value = '' // 重置搜索词
    } else {
      uni.showToast({ title: '用户数据加载失败', icon: 'none' })
    }
  } catch (error) {
    console.error('加载可用用户失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}


// 切换用户选中状态（多选）
const toggleUserSelection = (userId) => {
  const index = selectedUserIds.value.indexOf(userId)
  if (index > -1) {
    // 取消选中
    selectedUserIds.value.splice(index, 1)
  } else {
    // 选中
    selectedUserIds.value.push(userId)
  }
}

// 确认添加组员
const confirmAddMembers = async () => {
  if (selectedUserIds.value.length === 0) {
    uni.showToast({ title: '请至少选择一个用户', icon: 'none' })
    return
  }

  try {
    // 调用批量添加组员接口
    const res = await http.post(
      `/integral/organization/addMembers?orgId=${orgId.value}`,
      selectedUserIds.value
    )
    if (res.code === 200) {
      uni.showToast({ 
        title: `成功添加${selectedUserIds.value.length}位组员`, 
        icon: 'success' 
      })
      showUserDialog.value = false
      loadData(orgId.value) // 刷新组员列表
    } else {
      uni.showToast({ title: res.msg || '添加失败', icon: 'none' })
    }
  } catch (error) {
    console.error('添加组员失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}

// 分配积分给组员
const handleAssign = async (member) => {
  // 验证积分输入
  const points = Number(member.assignPoints)
  if (!member.assignPoints || isNaN(points) || points <= 0) {
    uni.showToast({ title: '请输入有效的积分', icon: 'none' })
    return
  }
	if(member.remark=='' || member.remark==null){
		uni.showToast({ title: '请输入积分描述', icon: 'none' })
		return
	}
  // 验证剩余积分是否足够
  if (points > remainingPoints.value) {
    uni.showToast({ title: '剩余积分不足', icon: 'none' })
    return
  }

  try {
    // 调用分配积分接口
    const res = await http.post(`/integral/organization/distrubuteAllocatedIntegral
	?userId=${uni.getStorageSync("userId")}&toUserId=${member.userId}&orgId=${orgId.value}
	&points=${member.assignPoints}&bOrgId=${member.orgId}`, {remark:member.remark})

    if (res.code === 200) {
      uni.showToast({ title: '积分分配成功', icon: 'success' })
      loadData(orgId.value) // 刷新数据
    } else {
      uni.showToast({ title: res.msg || '分配失败', icon: 'none' })
    }
  } catch (error) {
    console.error('积分分配失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}
// 分配积分给自己
const handleAssignBySelf = async () => {
  // 验证积分输入
  const points = Number(assignPoints.value)
  if (!assignPoints.value || isNaN(points) || points <= 0) {
    uni.showToast({ title: '请输入有效的积分', icon: 'none' })
    return
  }
  if(remark.value==''){
  	uni.showToast({ title: '请输入积分描述', icon: 'none' })
  	return
  }

  // 验证剩余积分是否足够
  if (points > remainingPoints.value) {
    uni.showToast({ title: '剩余积分不足', icon: 'none' })
    return
  }

  try {
	  const myId = uni.getStorageSync("userId")
    // 调用分配积分接口
    const res = await http.post(`/integral/organization/distrubuteAllocatedIntegral
	?userId=${myId}&toUserId=${myId}&orgId=${orgId.value}
	&points=${points}&bOrgId=${orgId.value}`,{remark:remark.value} )

    if (res.code === 200) {
      uni.showToast({ title: '积分分配成功', icon: 'success' })
	  setTimeout(()=>{
		  loadData(orgId.value) // 刷新数据
	  },1000)
	  
      
    } else {
      uni.showToast({ title: res.msg || '分配失败', icon: 'none' })
    }
  } catch (error) {
    console.error('积分分配失败:', error)
    uni.showToast({ title: '网络异常', icon: 'none' })
  }
}
// 删除组员
const handleDelete = async (memberId) => {
  uni.showModal({
    title: '确认移除',
    content: '确定要移除该组员吗(组员分配记录将被删除)？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await http.delete(`/integral/organization/user/${memberId}`)
          
          if (res.code === 200) {
            uni.showToast({ title: '移除成功', icon: 'success' })
            loadData(orgId.value) // 刷新列表
          } else {
            uni.showToast({ title: res.msg || '移除失败', icon: 'none' })
          }
        } catch (error) {
          console.error('移除组员失败:', error)
          uni.showToast({ title: '网络异常', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content {
  padding: 30rpx;
}

/* 积分信息卡片 */
.info-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20rpx;
  margin-bottom: 40rpx;
}

@media (min-width: 768px) {
  .info-cards {
    grid-template-columns: 1fr 1fr;
  }
}

.info-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  border-left: 8rpx solid;
}

.yellow {
  border-color: #fbbc05;
}

.blue {
  border-color: #4285f4;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 15rpx;
}

.card-value {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.5;
}

/* 通用标题样式 */
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
  display: block;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #eeeeee;
}

/* 添加组员区域 */
.add-member-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 40rpx;
}

.add-btn {
  background-color: #34a853;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  padding: 0 30rpx;
  height: 70rpx;
  font-size: 28rpx;
  width: 100%;
}

/* 组员列表区域 */
.members-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.members-list {
  margin-top: 20rpx;
}

.member-item {
  display: flex;
  flex-direction: column;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

@media (min-width: 768px) {
  .member-item {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.member-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.member-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.member-name {
  font-size: 30rpx;
  color: #333333;
  margin-right: 20rpx;
}

.member-points {
  font-size: 26rpx;
  color: #666666;
}

.member-operation {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.points-input {
  width: 160rpx;
  height: 60rpx;
  border: 2rpx solid #dddddd;
  border-radius: 8rpx;
  padding: 0 15rpx;
  font-size: 26rpx;
}

.distribute-btn {
  background-color: #9c27b0;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 60rpx;
  font-size: 26rpx;
}

.delete-btn {
  background-color: #ea4335;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 60rpx;
  font-size: 26rpx;
}

.empty-tip {
  text-align: center;
  padding: 50rpx 0;
  color: #999999;
  font-size: 28rpx;
}

/* 弹框样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  padding: 30rpx;
}

.dialog-container {
  width: 100%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.dialog-close {
  font-size: 40rpx;
  color: #999999;
  cursor: pointer;
}

/* 搜索框样式 */
.dialog-search {
  padding: 0 20rpx 20rpx;
}

.search-input {
  width: 100%;
  height: 60rpx;
  border: 2rpx solid #eeeeee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  background-color: #f9f9f9;
}

.dialog-body {
  max-height: 600rpx;
  overflow-y: auto;
  padding: 20rpx;
  margin-top: 10rpx;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
  background-color: #f9f9f9;
  cursor: pointer;
}

.user-item.selected {
  background-color: #e6f7ff;
  border: 1rpx solid #91d5ff;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 28rpx;
  color: #333333;
}

.user-id {
  font-size: 24rpx;
  color: #666666;
  margin-top: 5rpx;
}

.user-check {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: #4e5fff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
}

.dialog-footer {
  display: flex;
  border-top: 1rpx solid #eeeeee;
  position: relative;
}

.selected-count {
  position: absolute;
  left: 30rpx;
  line-height: 90rpx;
  color: #666;
  font-size: 26rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  font-size: 28rpx;
  border: none;
  background-color: transparent;
}

.cancel-btn {
  color: #666666;
  border-right: 1rpx solid #eeeeee;
}

.confirm-btn {
  color: #4e5fff;
  font-weight: bold;
}

.confirm-btn:disabled {
  color: #cccccc;
  cursor: not-allowed;
}
/* 组员操作区布局调整 */
.member-operation {
  display: flex;
  align-items: center;
  gap: 10rpx;
  flex-wrap: wrap; /* 允许换行，避免小屏幕拥挤 */
}

/* 备注输入框样式 */
.remark-input {
  flex: 1; /* 占剩余宽度 */
  min-width: 200rpx; /* 最小宽度，避免过窄 */
  height: 60rpx;
  border: 2rpx solid #dddddd;
  border-radius: 8rpx;
  padding: 0 15rpx;
  font-size: 26rpx;
}

/* 调整积分输入框宽度（避免过宽） */
.points-input {
  width: 120rpx; /* 比原来略窄，给备注框留空间 */
  height: 60rpx;
  border: 2rpx solid #dddddd;
  border-radius: 8rpx;
  padding: 0 15rpx;
  font-size: 26rpx;
}
</style>